home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / clang / cweb31.zip / EXAMPLES / WC.W < prev    next >
Text File  |  1993-01-10  |  9KB  |  240 lines

  1. % wc: An example of CWEB by Silvio Levy and Donald E. Knuth
  2.  
  3. \nocon % omit table of contents
  4. \datethis % print date on listing
  5. \def\SPARC{SPARC\-\kern.1em station}
  6.  
  7. @* An example of {\tt CWEB}.  This example, based on a program by
  8. Klaus Guntermann and Joachim Schrod [{\sl TUGboat\/ \bf7} (1986),
  9. 135--137] presents the ``word count'' program from \UNIX/, rewritten in
  10. \.{CWEB} to demonstrate literate programming in \CEE/.  The level of
  11. detail in this document is intentionally high, for didactic purposes;
  12. many of the things spelled out here don't need to be explained in
  13. other programs.
  14.  
  15. The purpose of \.{wc} is to count lines, words, and/or characters in a
  16. list of files. The number of lines in a file is the number of newline
  17. characters it contains. The number of characters is the file length in bytes.
  18. A ``word'' is a maximal sequence of consecutive characters other than
  19. newline, space, or tab, containing at least one visible ASCII code.
  20. (We assume that the standard ASCII code is in use.)
  21.  
  22. @ Most \.{CWEB} programs share a common structure.  It's probably a
  23. good idea to state the overall structure explicitly at the outset,
  24. even though the various parts could all be introduced in unnamed
  25. sections of the code if we wanted to add them piecemeal.
  26.  
  27. Here, then, is an overview of the file \.{wc.c} that is defined
  28. by this \.{CWEB} program \.{wc.w}:
  29.  
  30. @c
  31. @<Header files to include@>@/
  32. @<Global variables@>@/
  33. @<Functions@>@/
  34. @<The main program@>
  35.  
  36. @ We must include the standard I/O definitions, since we want to send
  37. formatted output to |stdout| and |stderr|.
  38.  
  39. @<Header files...@>=
  40. #include <stdio.h>
  41.  
  42. @  The |status| variable will tell the operating system if the run was
  43. successful or not, and |prog_name| is used in case there's an error message to
  44. be printed.
  45.  
  46. @d OK 0 /* |status| code for successful run */
  47. @d usage_error 1 /* |status| code for improper syntax */
  48. @d cannot_open_file 2 /* |status| code for file access error */
  49.  
  50. @<Global variables@>=
  51. int status=OK; /* exit status of command, initially |OK| */
  52. char *prog_name; /* who we are */
  53.  
  54. @ Now we come to the general layout of the |main| function. 
  55.  
  56. @<The main...@>=
  57. main (argc,argv)
  58.     int argc; /* the number of arguments on the \UNIX/ command line */
  59.     char **argv; /* the arguments themselves, an array of strings */
  60. {
  61.   @<Variables local to |main|@>@;
  62.   prog_name=argv[0];
  63.   @<Set up option selection@>;
  64.   @<Process all the files@>;
  65.   @<Print the grand totals if there were multiple files @>;
  66.   exit(status);
  67. }
  68.  
  69. @ If the first argument begins with a `\.{-}', the user is choosing
  70. the desired counts and specifying the order in which they should be
  71. displayed.  Each selection is given by the initial character
  72. (lines, words, or characters).  For example, `\.{-cl}' would cause
  73. just the number of characters and the number of lines to be printed,
  74. in that order.
  75.  
  76. We do not process this string now; we simply remember where it is.
  77.  It will be used to control the formatting at output time.
  78.  
  79. @<Var...@>=
  80. int file_count; /* how many files there are */
  81. char *which; /* which counts to print */
  82.  
  83. @ @<Set up o...@>=
  84. which="lwc"; /* if no option is given, print all three values */
  85. if (argc>1 && *argv[1] == '-') { which=argv[1]+1; argc--; argv++; }
  86. file_count=argc-1;
  87.  
  88. @ Now we scan the remaining arguments and try to open a file, if
  89. possible.  The file is processed and its statistics are given.
  90. We use a |do|~\dots~|while| loop because we should read from the
  91. standard input if no file name is given.
  92.  
  93. @<Process...@>=
  94. argc--;
  95. do@+{
  96.   @<If a file is given, try to open |*(++argv)|; |continue| if unsuccessful@>;
  97.   @<Initialize pointers and counters@>;
  98.   @<Scan file@>;
  99.   @<Write statistics for file@>;
  100.   @<Close file@>;
  101.   @<Update grand totals@>; /* even if there is only one file */
  102. }@+while (--argc>0);
  103.  
  104. @ Here's the code to open the file.  A special trick allows us to
  105. handle input from |stdin| when no name is given.
  106. Recall that the file descriptor to |stdin| is~0; that's what we
  107. use as the default initial value.
  108.  
  109. @<Variabl...@>=
  110. int fd=0; /* file descriptor, initialized to |stdin| */
  111.  
  112. @ @d READ_ONLY 0 /* read access code for system |open| routine */
  113.  
  114. @<If a file...@>=
  115. if (file_count>0 && (fd=open(*(++argv),READ_ONLY))<0) {
  116.   fprintf (stderr, "%s: cannot open file %s\n", prog_name, *argv);
  117. @.cannot open file@>
  118.   status|=cannot_open_file;
  119.   file_count--;
  120.   continue;
  121. }
  122.  
  123. @ @<Close file@>=
  124. close(fd);
  125.  
  126. @ We will do some homemade buffering in order to speed things up: Characters
  127. will be read into the |buffer| array before we process them.
  128. To do this we set up appropriate pointers and counters.
  129.  
  130. @d buf_size BUFSIZ /* \.{stdio.h}'s |BUFSIZ| is chosen for efficiency*/
  131.  
  132. @<Var...@>=
  133. char buffer[buf_size]; /* we read the input into this array */
  134. register char *ptr; /* the first unprocessed character in |buffer| */
  135. register char *buf_end; /* the first unused position in |buffer| */
  136. register int c; /* current character, or number of characters just read */
  137. int in_word; /* are we within a word? */
  138. long word_count, line_count, char_count; /* number of words, lines, 
  139.     and characters found in the file so far */
  140.  
  141. @ @<Init...@>=
  142. ptr=buf_end=buffer; line_count=word_count=char_count=0; in_word=0;
  143.  
  144. @ The grand totals must be initialized to zero at the beginning of the
  145. program. If we made these variables local to |main|, we would have to
  146. do this initialization explicitly; however, \CEE/'s globals are automatically
  147. zeroed. (Or rather, ``statically zeroed.'') (Get it?)
  148. @^Joke@>
  149.  
  150. @<Global var...@>=
  151. long tot_word_count, tot_line_count, tot_char_count;
  152.  /* total number of words, lines, and chars */
  153.  
  154. @ The present section, which does the counting that is \.{wc}'s {\it raison
  155. d'\^etre}, was actually one of the simplest to write. We look at each
  156. character and change state if it begins or ends a word.
  157.  
  158. @<Scan...@>=
  159. while (1) {
  160.   @<Fill |buffer| if it is empty; |break| at end of file@>;
  161.   c=*ptr++;
  162.   if (c>' ' && c<0177) { /* visible ASCII codes */
  163.     if (!in_word) {word_count++; in_word=1;}
  164.     continue;
  165.   }
  166.   if (c=='\n') line_count++;
  167.   else if (c!=' ' && c!='\t') continue;
  168.   in_word=0; /* |c| is newline, space, or tab */
  169. }
  170.  
  171. @ Buffered I/O allows us to count the number of characters almost for free.
  172.  
  173. @<Fill |buff...@>=
  174. if (ptr>=buf_end) {
  175.   ptr=buffer; c=read(fd,ptr,buf_size);
  176.   if (c<=0) break;
  177.   char_count+=c; buf_end=buffer+c;
  178. }
  179.  
  180. @ It's convenient to output the statistics by defining a new function
  181. |wc_print|; then the same function can be used for the totals.
  182. Additionally we must decide here if we know the name of the file
  183. we have processed or if it was just |stdin|.
  184.  
  185. @<Write...@>=
  186. wc_print(which, char_count, word_count, line_count);
  187. if (file_count) printf (" %s\n", *argv); /* not |stdin| */
  188. else printf ("\n"); /* |stdin| */
  189.  
  190. @ @<Upda...@>=
  191. tot_line_count+=line_count;
  192. tot_word_count+=word_count;
  193. tot_char_count+=char_count;
  194.  
  195. @ We might as well improve a bit on \UNIX/'s \.{wc} by displaying the
  196. number of files too.
  197.  
  198. @<Print the...@>=
  199. if (file_count>1) {
  200.   wc_print(which, tot_char_count, tot_word_count, tot_line_count);
  201.   printf(" total in %d files\n",file_count);
  202. }
  203.  
  204. @ Here now is the function that prints the values according to the
  205. specified options.  The calling routine is supposed to supply a
  206. newline. If an invalid option character is found we inform
  207. the user about proper usage of the command. Counts are printed in
  208. 8-digit fields so that they will line up in columns.
  209.  
  210. @d print_count(n) printf("%8ld",n)
  211.  
  212. @<Fun...@>=
  213. wc_print(which, char_count, word_count, line_count)
  214. char *which; /* which counts to print */
  215. long char_count, word_count, line_count; /* given totals */
  216. {
  217.   while (*which) 
  218.     switch (*which++) {
  219.     case 'l': print_count(line_count); break;
  220.     case 'w': print_count(word_count); break;
  221.     case 'c': print_count(char_count); break;
  222.     default: if ((status & usage_error)==0) {
  223.         fprintf (stderr, "\nUsage: %s [-lwc] [filename ...]\n", prog_name);
  224. @.Usage: ...@>
  225.         status|=usage_error;
  226.       }
  227.     }
  228. }
  229.  
  230. @ Incidentally, a test of this program against the system \.{wc}
  231. command on a \SPARC\ showed that the ``official'' \.{wc} was slightly
  232. slower. Furthermore, although that \.{wc} gave an appropriate error
  233. message for the options `\.{-abc}', it made no complaints about the
  234. options `\.{-labc}'! Dare we suggest that the system routine might have been
  235. better if its programmer had used a more literate approach?
  236.  
  237. @* Index.
  238. Here is a list of the identifiers used, and where they appear. Underlined
  239. entries indicate the place of definition. Error messages are also shown.
  240.